package com.fzu.ess.common.Model;/**
 * Created by ercha on 2016/1/8.
 */

import lombok.Data;

import java.util.Map;

/**
 * @author ercha
 * @ClassName: FilterClass
 * @Description:
 * @Date 2016/01/08 12:56
 * @History:// 历史修改记录
 * <author>  // 修改人1
 * <time>    // 修改时间
 * <desc>    // 描述修改内容
 */
@Data
public class FilterRule {
    //字段的 java 类型
    private String type;

    //key 为操作,如 "eq","gt"..
    //value 为值
    private Map<String, String> filter;

    public String addRule(String entityName, String prop){
        String res = " ";
        String c = " " + entityName + "." + prop + " ";

        //遍历每个 FilterRule 的条件
        for(Map.Entry e: filter.entrySet()){
            String op = e.getKey().toString();
            String value = e.getValue().toString();

            op = convertOp(op);
            res += c + op;
            switch (op){
                case " like ":
                    res += "'%" + value + "%' and "; break;
                case " in ":
                    res += "(" + value + ") and"; break;
                default:
                    if(type.equalsIgnoreCase("string")){
                        res += "'" + value + "' and ";
                    }else if(type.equalsIgnoreCase("int")){
                        res += value + " and ";
                    }else if(type.equalsIgnoreCase("float")){
                        res += value + " and ";
                    }
            }
        }
        return res;
    }

    /**
     * 将前台传来的 op 设置成 hibernate 格式
     * @param op
     * @return
     */
    private String convertOp(String op){
        switch (op) {
            case "eq":
                return " = ";
            case "ne":
                return " != ";
            case "lt":
                return " < ";
            case "gt":
                return " > ";
            case "like":
                return " like ";
            case "in":
                return " in ";
            default:
                return "";
        }
    }
}
